import { useState, useEffect, useRef } from 'react';
import { message } from 'antd';
import moment from 'moment';
import FormRender from '@/components/FormRender';
import { useResize } from '@/hooks/useResize';
import CommonTable from '@/components/CommonTable';
import CommonPagination from '@/components/CommonPagination';
import OperaBtnRender from '@/components/OperaBtnRender';
import { formatAmount, commonExportForPage } from '@/utils/utils.jsx';
import { getDeducationTableDataOp } from '../service';
import RelativeModal from './RelativeModal';

const initPagination = {
	current: 1,
	total: 0,
	pageSize: 20,
	showQuickJumper: true,
	pageSizeOptions: [20, 50, 100, 500],
}

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const formArr = [
	{
		itemConfig: {
			name: 'time'
		},
		elConfig: {
			formType: 'rangTime',
			placeholder: ['开始时间', '结束时间'],
			prefix: '时间',
			disabledDate: current => current && current > moment().endOf('day')
		}
	},
	{
		itemConfig: {
			name: 'types'
		},
		elConfig: {
			allowClear: false,
			formType: 'Select',
			placeholder: '订单类型',
			options: [
				{ label: '调整拿货抵扣', value: '0' },
				{ label: '拿货退货入账', value: '1' },
				{ label: '无订单退货入账', value: '44' },
				{ label: '拿货抵扣', value: '2' },
				{ label: '撤销拿货', value: '3' },
				{ label: '采购退货入账', value: '4' },
				{ label: '采购抵扣', value: '5' },
				{ label: '调整采购抵扣', value: '6' },
				{ label: '拆分装箱', value: '33' },
			]
		}
	},
	{
		itemConfig: {
			name: 'tradeNo'
		},
		elConfig: {
			formType: 'Input',
			placeholder: '流水单号',
		}
	},
	{
		itemConfig: {
			name: 'omsOrderSn'
		},
		elConfig: {
			formType: 'Input',
			placeholder: '系统单号',
		}
	},
]

export default ({ stepObj, accountMsg }) => {

	const { merchantNo } = stepObj;

	const [query, setQuery] = useState({
		merchantNo, time: [moment().startOf('day').subtract(89, 'days'), moment().endOf('day')]
	});
	const [filter, setFilter] = useState({});
	const [pagination, setPagination] = useState(null); //分页数据

	//监听变更
	const { el: headerEl, height: headerHeight } = useResize();

	const [data, setData] = useState([]);

	const [records, setRecords] = useState({});

	const stageParams = useRef({});

	useEffect(() => {
		if (query) {
			setPagination({
				...(pagination || initPagination),
				current: 1
			})
		}
	}, [query, filter])

	useEffect(() => {
		if (pagination) {
			getTableListFunc();
		}
	}, [pagination])

	const getTableListFunc = async () => {
		START_LOADING();
		const params = {
			...query,
			...filter,
			merchantNo,
			accountNo: accountMsg.accountNo,
			size: pagination.pageSize,
			current: pagination.current,
			time: undefined
		}
		if (query?.time) {
			params.timeStart = moment(query.time[0]._d).format(dateFormat);
			params.timeEnd = moment(query.time[1]._d).format(dateFormat);
		}
		stageParams.current = params;
		const { data, success } = await getDeducationTableDataOp(params);
		if (success) {
			const { records = [], total = 0 } = data || {};
			pagination.total = total;
			setData(records);
		}
		END_LOADING();
	}

	//表单渲染组件
	const FormRenderProps = {
		query,
		formArr,
		formConfig: {
			name: 'store-detail-form',
			style: { marginBottom: '16px' }
		},
		clickSearch(val) {
			setQuery(val);
		},
		clickReset() {
			setQuery({ merchantNo, time: [moment().startOf('day').subtract(89, 'days'), moment().endOf('day')] })
		},
	}

	//展示列
	const columns = [
		{
			title: '序号',
			dataIndex: 'index',
			key: 'index',
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: '抵扣单号',
			dataIndex: 'tradeNo',
			key: 'tradeNo',
			width: 140,
			render: (text, record) => <>
				{
					(record.type == 0 || record.type == 6) ? <span className='common-color9'>—</span>
						: <span className='common-color3' style={{ fontWeight: 500 }}>{text}</span>
				}
				<p>{record.createTime}</p>
			</>
		},
		{
			title: '抵扣类型',
			dataIndex: 'typeText',
			key: 'typeText',
			width: 120,
			render: (text, { type }) =>
				<>
					{
						(type == 0 || type == 6) ? <span className='common-color13'>{text}</span>
							: <span className={[2, 5].includes(type) ? 'common-color10' : 'common-color9'}>{text}</span>
					}
				</>
		},
		{
			title: '收支金额（元）',
			dataIndex: 'amount',
			key: 'amount',
			width: 140,
			filteredValue: filter.costType ? [filter.costType] : null,
			filters: [
				{ text: '收入', value: '1' },
				{ text: '支出', value: '2' },
			],
			filterMultiple: false,
			render: (text, { type }) => {
				if (!text?.includes('-')) {//[2].includes(type)
					return <span className='common-color9' style={{ fontWeight: 500 }}>+{formatAmount(Number(text))}</span>
				} else {
					return <span className='common-color10' style={{ fontWeight: 500 }}>{formatAmount(Number(text))}</span>
				}
			}
		},
		{
			title: '当前余额',
			dataIndex: 'currentAvailBalance',
			key: 'currentAvailBalance',
			width: 120,
			render: text => <span className='common-color4'>{formatAmount(text)}</span>
		},

		{
			title: '操作',
			dataIndex: 'operator',
			key: 'operator',
			width: 100,
			fixed: 'right',
			render: (text, record) =>
				<>
					{
						(record.type == 0 || record.type == 6) ? <span className='common-color9'>—</span>
							: <span className='common-color1' style={{ cursor: 'pointer' }} onClick={() => setRecords({ ...record, visible: 'relative' })}>关联订单号</span>
					}
				</>
		}
	];

	const tableProps = {
		data,
		columns,
		scroll: { y: `calc(100vh - ${headerHeight + 294}px)` },
		onChange(_, filter) {
			const { amount } = filter;
			if (amount) {
				setFilter({ costType: amount[0] });
			} else {
				setFilter({});
			}
		}
	}

	const pageProps = {
		pagination,
		style: {
			marginTop: '12px'
		},
		handleChange(current, size) {
			setPagination({
				...pagination,
				current: current == pagination.current ? 1 : current,
				pageSize: size
			})
		},
	};

	const relativeModalProps = {
		records,
		handleClose() {
			setRecords({});
		}
	}

	const handleExport = () => {
		if (pagination.total) {
			START_LOADING();
			let timer = setTimeout(() => {
				message.info('浏览器即将为您处理导出');
				END_LOADING();
				clearTimeout(timer);
				timer = null;
			}, 600)
		}
		commonExportForPage({
			total: pagination.total,
			params: stageParams.current,
			method: 'get',
			url: '/zjf-pays/deductionPayOrder/exportNew',
			name: '门店抵扣详情导出'
		})
	}

	//操作按钮
	const btnArr = [
		{ elType: 'button', text: '导出订单', onClick: handleExport }
	]

	return (
		<>
			<div ref={headerEl}>
				<FormRender {...FormRenderProps} />
			</div>
			<div className='global-page-wrap'>
				<OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
				<CommonTable {...tableProps} />
				<CommonPagination {...pageProps} />
			</div>
			{records?.visible == 'relative' && <RelativeModal {...relativeModalProps} />}
		</>
	)
}